package com.moyu.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.moyu.common.core.enums.ResultCode;
import com.moyu.common.security.exception.ServiceException;
import com.moyu.user.domain.permission.Permission;
import com.moyu.user.domain.permission.dto.PermissionQueryDTO;
import com.moyu.user.domain.permission.dto.PermissionSaveDTO;
import com.moyu.user.domain.permission.vo.PermissionListVO;
import com.moyu.user.mapper.PermissionMapper;
import com.moyu.user.service.IPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 权限服务实现类
 *
 * @Author 赵彦博
 * @Date 2025/3/25 18:30
 */
@Slf4j
@Service
public class PermissionServiceImpl implements IPermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public List<PermissionListVO> list(PermissionQueryDTO permissionQueryDTO) {
        PageHelper.startPage(permissionQueryDTO.getPageNum(), permissionQueryDTO.getPageSize());
        return permissionMapper.selectPermissionList(permissionQueryDTO);
    }

    @Override
    public boolean deletePermission(Long permissionId) {
        return permissionMapper.deletePermissionById(permissionId) > 0;
    }

    @Override
    public int addPermission(PermissionSaveDTO permissionSaveDTO) {
        LambdaQueryWrapper<Permission> queryWrapper = new LambdaQueryWrapper<>();
        Permission permission = permissionMapper.selectOne(queryWrapper
                .eq(Permission::getPermissionName, permissionSaveDTO.getPermissionName()));
        // 检查权限名称是否已存在
        if (permission != null) {
            throw new ServiceException(ResultCode.AILED_PERMISSION_EXISTS);
        }
        Permission insertPermission = new Permission();
        insertPermission.setPermissionName(permissionSaveDTO.getPermissionName());
        insertPermission.setRequestMethod(permissionSaveDTO.getRequestMethod());
        insertPermission.setRouterPath(permissionSaveDTO.getRouterPath());
        insertPermission.setType(permissionSaveDTO.getType());
        // 插入权限信息
        return permissionMapper.insert(insertPermission);
    }
}
